<template>
  <div class="passward">
    <el-form label-width="auto" style="max-width: 600px" ref='selfFormRef' :model='passordValue' :rules='selfRules'>
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input show-password placeholder='请输入原来的密码' v-model.trim="passordValue.oldPassword" />
      </el-form-item>

      <el-form-item label="新密码" prop="password">
        <el-input  show-password placeholder='密码格式为数字字母下划线6-30位' v-model.trim="passordValue.password" />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input   @blur="checkPass"  show-password placeholder='请再次确认密码' v-model.trim="passordValue.confirmPassword" />
      </el-form-item>

      <el-form-item>
        <div class="buttons">
          <el-button type='primary' class='saveBtn' :loading="loadingRef" @click='saveForm'>
            保存
          </el-button>
        </div>
      </el-form-item>

    </el-form>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue"
import { ElMessage } from 'element-plus';
import { upUserInfo } from "@/api/login"
import { upPassword} from "@/api/user" 
import { useRouter } from "vue-router";
const router=useRouter()
const { proxy } = getCurrentInstance();
const loadingRef = ref(false)
const passordValue = ref({
  oldPassword: "",
  password: '',
  confirmPassword: ""
})
// 获取基本信息
onMounted(() => {

})


//表结构验证规则
const selfRules = ref({
  oldPassword: [
    { required: true, message: '旧密码必须填写', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '新密码必须填写', trigger: 'blur' },
    { min: 6, max: 30, message: '新密码的长度必须在6到30位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '确认密码必须填写', trigger: 'blur' },
  ],

});


// 点击保存
const saveForm = () => {
  proxy.$refs.selfFormRef.validate(valid => {
    if (valid) {
      // 这里判断旧密码是否正确          

      let data = {
        "old_password": passordValue.value.oldPassword,
        "new_password": passordValue.value.password
      }

      upPassword(data).then(res => {
        console.log(res);
        if (!res) {
          ElMessage.success("密码修改成功")
          proxy.$refs.selfFormRef.resetFields();

            sessionStorage.clear()
            localStorage.clear()
            router.push("/login")
          return
        }
        ElMessage.error(res.response.data)
      })
      return
    }

  })

}


// 确认密码离开焦点
const checkPass=()=>{
    if(passordValue.value.confirmPassword!==passordValue.value.password){

      ElMessage.error("两次密码输入不一致")
    }
}
</script>

<style lang="scss" scoped>
.passward {
  padding: 50px 0 0 50px;
}


.buttons {
  padding: 10px 70px 40px;
}

.saveBtn {
  font-size: 14px;
}

.el-input {
  width: 300px;
}
</style>